#include "TheApp.hpp"
//#include "cybertron/core/UtilUrlRequest.hpp"
#include "cybertron/core/Log.hpp"
#include "cybertron/core/UtilPath.hpp"
#include "cybertron/core/Thread.hpp"
#include "cybertron/core/UtilConsole.hpp"
#include "cybertron/core/UtilCRT.hpp"
#include "cybertron/node/StartupArguments.hpp"
#include "cybertron/core/CoreVersion.hpp"
#include "cybertron/core/SimOneEnv.hpp"
#include "cybertron/core/UtilUuidxx.hpp"
#include "Sensor/Vehicle.pb.h"
#include "Sensor/SensorCommon.pb.h"
#include <iostream>
#include <fstream>
#include <chrono>
#ifdef CYBERTRON_LINUX
#include <unistd.h>
#include <stdlib.h>  
#include <signal.h>
#endif
// determined by the EnvVar LOG_CONSOLE outside on the windows
//#if defined(CYBERTRON_WIN) && defined(NDEBUG)
//#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
//#endif

using namespace cybertron;

//
static UtilCRTAutoInitialize sCRT;

#ifdef CYBERTRON_LINUX
bool gRunning = true;
void sigterm_handler(int no) {
	gRunning = false;
	logInfo("recv sigterm_handler exit....%d", no);
}
#endif

TheApp::TheApp()
{
	mbRunning = true;
}
TheApp::~TheApp()
{
	
}


//BaseApp
//////////////////////////////////////
void TheApp::getVerion()
{
	std::string version = getVersionOnCore("CybertronWork", "20210626154200");
	logInfo("%s", version.c_str());
}



int TheApp::run()
{
	UtilCRT::call("runDaemon", [this]() {
		this->runDaemon();
	});

	return 0;
}

void TheApp::runDaemon(){

	//while (true)
	//{
	//	std::this_thread::sleep_for(std::chrono::seconds(1));
	//	Common::EWorkNodeState s = mWorkState.load(memory_order_relaxed);
	//	if (s == Common::EWorkNodeStateEndingWork) {
	//		logInfo("################1work stat = %d", s);
	//		return;
	//	}
	//	else if (s >= Common::EWorkNodeStateInitFinish) {
	//		logInfo("################2work stat = %d", s);
	//		break ;
	//	}
	//} 

	while(mbRunning){
#ifdef CYBERTRON_LINUX
	signal(SIGTERM, sigterm_handler);
#endif
	std::this_thread::sleep_for(std::chrono::milliseconds(100));
	/*if (!isRunning()){
		break;
	}*/
	WorkAppWithHotArea::handleTimer();
	}
	stopRunning();
}

//WorkApp
///////////////////////////////////////////////////
void TheApp::onWorkNodeStop(){
	logInfo("my test work node is stop.");
	stopRunning();
}
void TheApp::testThread() {
	/*int count = 0;
	while (true)
	{
		if (count > 5) {
			
			
			break;
		}
		count += 1;
		logInfo("testThread==========>%d", count);
		std::this_thread::sleep_for(std::chrono::milliseconds(1000));
	}

	
	while (true)
	{
		sendGetWorkDynamicConfig("", Common::EWorkNodeType_CybertronNodeTimer);
		Common::SyncWorkNodeDynamicConfig config;
		bool ret = getWorkDynamicConfig(Common::EWorkNodeType_CybertronNodeTimer, &config);
		if (!ret) {
			std::this_thread::sleep_for(std::chrono::milliseconds(1000));
			continue;
		}
		logInfo("Common::SyncWorkNodeDynamicConfig ====>%d %s:%d", config.taskid().c_str(),config.workpublicip().c_str(),config.workpublicport());
		break;
		
	}*/
	return;
}

bool TheApp::onLoadConfig() {
	if (!WorkAppWithHotArea::onLoadConfig()) {
		return false;
	}
	return true;
}
bool TheApp::onConnectNodeTimerAfter() {
	if (!WorkAppWithHotArea::onConnectNodeTimerAfter()) {
		return false;
	}
	return true;
}

bool TheApp::onTaskStart() {
	logInfo("onTaskStart");
	connectNodeTimer();
	return true;
}

bool TheApp::onTaskRunning() {
	logInfo("onTaskRunning");
	//mHotAreaManager.setTaskRunning("1234");
	return true;
}

bool TheApp::onTaskStop() {
	logInfo("onTaskStop");
	mbRunning = false;
	return true;
}



//WorkAppWithHotArea
/////////////////////////////////////
bool TheApp::onStart(){
	logInfo("WorkNodeWithHotarea test, on start");
	return true;
}

void TheApp::onTimer(int framestamp, int ms){
	const std::vector<std::shared_ptr<TrafficActorHotArea>> &hotAreas = mHotAreaManager.getHotAreas();
	for (const auto& pHotArea : hotAreas) {
		for (const auto& actorId : pHotArea->getActorIdSet()) {
			const TrafficActor &actor = pHotArea->getActor(actorId);
			if (actor.getActorType() != HotArea::EActorType_MainVehicle) {
				continue;
			}
			vec3 pos = actor.getWorldPosition();
			vec3 rot = actor.getWorldRotation();
			
			HotArea::MainVehiclePrivateData MainVehiclePrivateData;
			actor.getCustomProperties(MainVehiclePrivateData);
		}
	}
	//std::vector<std::string> workIdList;
	//getWorkIdListByType(Common::EWorkNodeType_CybertronVehicle, workIdList);

	//CybertronSyncConn client;
	//if (connectWorkServer(workIdList[0], client)) {
	//	cybertron::proto::sensor::DataVehicleBodyState state;
	//	client.send(proto::sensor::EDataType_VehicleBodyState, state);
	//}
	
	
	
}

void TheApp::onTimer(int framestamp, int ms, int msModNs){
	// logInfo("WorkNodeWithHotarea test, on Timer2");
}

void TheApp::onPlay(){
	logInfo("WorkNodeWithHotarea test, on Play");
}

void TheApp::onPause(){
	logInfo("WorkNodeWithHotarea test, on Pause");
}

void TheApp::onReset(){
	logInfo("WorkNodeWithHotarea test, on Reset");
}

std::string TheApp::onControlCommand(const std::string controlCommand){
	logInfo("WorkNodeWithHotarea test, on Control Command: %s", controlCommand.c_str());
	return controlCommand;
}

void TheApp::onEnd(){
	logInfo("WorkNodeWithHotarea test, on End");
}

void TheApp::onEnd(Common::ETaskEndReason reason){
	logInfo("WorkNodeWithHotarea test, on End with reason");
}

void TheApp::onCaseStart(){
	logInfo("WorkNodeWithHotarea test, on CaseStart");
}

void TheApp::onCaseStop(){
	logInfo("WorkNodeWithHotarea test, on CaseStop");
}